//
//  ItemsViewController.m
//  me.huanghai.shanghanlun
//
//  Created by hh on 16/10/11.
//  Copyright © 2016年 hh. All rights reserved.
//

#import "ItemsViewController.h"
#import "AppDelegate.h"
#import "TranlucentToolbar.h"

@interface ItemsViewController () <UISearchBarDelegate>
{
    NSArray<SectionData *> *dataBac;
    NSArray<SectionData *> *data;
    
    UISearchBar *searchBar;
}
@end

@implementation ItemsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    [self setupSearchBarCloseBtn];
    self.navigationItem.titleView = searchBar;
    dataBac = [AppDelegate sharedApp].itemData;
    data = dataBac;
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)setupSearchBarCloseBtn
{
    TranlucentToolbar *tb = [[TranlucentToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    tb.tintColor = [UIColor redColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 50, 30);
    [btn setImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
    btn.layer.cornerRadius = 6;
    btn.layer.borderWidth = 0.5;
    [btn addTarget:self action:@selector(inputComplete:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *finish = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    tb.items = @[space, finish];
    searchBar.inputAccessoryView = tb;
}

-(void)inputComplete:(id)sender
{
    [searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        data = dataBac;
        [self.tableView reloadData];
        return;
    }
    
    // 根据空格切割搜索词
    NSArray<NSString *> *words = [searchText componentsSeparatedByString:@" "];
    
    // 删除掉数组空项
    words = [words filter:^BOOL(NSString *obj) {
        return obj.length > 0;
    }];
    
    // 获取没有-以及#的搜索词数组
    NSArray<NSString *> *wordsContent = [words map:^NSString *(NSString *obj, NSInteger idx) {
        NSString *tmp = [obj stringByReplacingOccurrencesOfString:@"-" withString:@""];
        tmp = [tmp stringByReplacingOccurrencesOfString:@"#" withString:@"."];
        return tmp;
    }];
    // 用以上2个数组组成字典，这么做是为了运行效率，不必每次重复做消除-和#的事，又能保留足够信息。
    NSDictionary<NSString *, NSString *> *wordsDict = [NSDictionary dictionaryWithObjects:wordsContent forKeys:words];
    
    // 先筛选里头，再筛选外头的数组，所以先map后filter，为了运行效率。
    data = [dataBac map:^SectionData *(SectionData *sec, NSInteger idx) {
        SectionData *res = [SectionData new];
        res.section = sec.section;
        res.header = sec.header;
        
        // 筛选条目
        res.data = [sec.data filter:^BOOL(ItemData *item) {
            return [words every:^BOOL(NSString *word) {
                NSString *w = wordsDict[word];
                BOOL res = [item.text.string containsString:w];
                return [word containsString:@"-"] ? !res : res;
            }];
        // 筛完渲染搜索词
        } thenMap:^id(ItemData *item) {
            ItemData *res = item.mutableCopy;
            [words forEach:^(NSString *word, NSInteger idx) {
                if ([word containsString:@"-"]) {
                    // 如果有排除符号，则跳过渲染
                    return;
                }
                [self renderMatchedText:wordsDict[word] inAttributedString:res.text];
            }];
            return res;
        }];
        return res;
    } thenFilter:^BOOL(SectionData *sec) {
        return sec.data.count > 0;
    }];
    
    [self.tableView reloadData];
}

- (void)renderMatchedText:(NSString *)word inAttributedString:(NSMutableAttributedString *)astr
{
    // 对所有匹配的子串进行染色
    // 因为匹配上的所有子串都要染色，需要防止通配符导致全部染色的情况
    NSRange once = [word rangeOfString:@"\\.*" options:NSRegularExpressionSearch range:NSMakeRange(0, word.length)];
    BOOL onlyOnce = NO;
    if (once.length == word.length) {
        onlyOnce = YES;
    }
    NSInteger length = astr.string.length;
    NSRange range, searchRange = NSMakeRange(0, length);
    while ((range = [astr.string rangeOfString:word options:NSRegularExpressionSearch range:searchRange]).location != NSNotFound) {
        if (range.length == 0) {
            NSUInteger loc = range.location + 1;
            if (loc >= length) {
                break;
            }
            searchRange = NSMakeRange(loc, length - loc);
            continue;
        }

        [astr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        [astr addAttribute:NSStrokeWidthAttributeName value:@(-4) range:range];
        NSUInteger loc = NSMaxRange(range);
        searchRange = NSMakeRange(loc, length - loc);
        
        if (onlyOnce) {
            break;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return data[section].data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"items" forIndexPath:indexPath];
    
    ItemData *item = data[indexPath.section].data[indexPath.row];
    cell.contentLabel.attributedText = item.text;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    SectionData *sec = data[section];
    return sec.header;
}


@end
